package com.petRescueCenter.demo.user.entity.dto;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import com.petRescueCenter.demo.user.entity.User;

public class UserQueryDTO {
	private Long userId;
	private String name;

	public Long getUserId() {
		return userId;
	}

	public String getName() {
		return name;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public void setName(String name) {
		this.name = name;
	}

	@SuppressWarnings({ "serial" })
	public static Specification<User> getWhereClause(final UserQueryDTO userQueryDTO) {
		return new Specification<User>() {
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> predicate = new ArrayList<>();

				if (null != userQueryDTO.getUserId()) {
					predicate.add(criteriaBuilder.equal(root.get("id").as(Long.class), userQueryDTO.getUserId()));
				}

				if (StringUtils.isNotBlank(userQueryDTO.getName())) {
					predicate.add(criteriaBuilder.like(root.get("name").as(String.class),
							"%" + userQueryDTO.getName() + "%"));
				}

				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		};
	}
}
